package com.open.pingban.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.open.pingban.MainActivity;
import com.open.pingban.R;
import com.open.pingban.activity.OpenFileActivity;
import com.open.pingban.adapter.DocAdapter;
import com.open.pingban.mode.DocData;
import com.open.pingban.presenter.DocPresenter;
import com.open.pingban.presenter.IDoc;
import com.open.pingban.utils.Constant;
import com.open.pingban.utils.OPENLOG;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cz.msebera.android.httpclient.Header;

/**
 * 文档 界面.
 */
public class DocFragment extends BaseView {

    @InjectView(R.id.doc_gridview)
    GridView docGridview;

    IDoc mDocPresenter = new DocPresenter();
    DocAdapter mDocAdapter = new DocAdapter();
    DocData mDocData;

    public DocFragment(Activity activity) {
        super(activity);
    }

    public static DocFragment newInstance(Activity activity) {
        DocFragment newFragment = new DocFragment(activity);
        return newFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater) {
        View rootView = inflater.inflate(R.layout.fragment_doc, null, false);
        ButterKnife.inject(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated() {
        docGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mDocData != null && mDocData.getDocs() != null) {
                    ((MainActivity)getActivity()).stopAllVideoAndAudio(-1);
                    DocData.DocInfo info = mDocData.getDocs().get(position);
                    //  使用对应的APK打开文件.
                    // 首先需要下载，才能本地打开，R.
                    String url = info.getUrl();
                    String name = info.getName();
                    Intent intent = new Intent(getActivity(), OpenFileActivity.class);
                    intent.putExtra("downUrl", url);
                    name = getFileName(url);
                    intent.putExtra("fileName", name);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            }
        });
        docGridview.setAdapter(mDocAdapter);
        updateNetWorkView();
    }

    @Override
    public void updateNetWorkView() {
        mUpdateHander.sendEmptyMessageDelayed(-250, 1800);
    }

    Handler mUpdateHander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                getDocLists();
            } catch (Exception e) {
                OPENLOG.E("" + e.getMessage());
                e.printStackTrace();
            }
        }
    };

    private String getFileName(String url) {
        String fileName = "";
        int startIndex = url.lastIndexOf("/");
        fileName = startIndex != -1 ? url.substring(startIndex) : url;
        return fileName;
    }

    /**
     * 获取文档列表.
     */
    private void getDocLists() {
        OPENLOG.D(Constant.GET_DOC_URL);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        asyncHttpClient.get(Constant.ROOT_ADDR + Constant.GET_DOC_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                try {
                    String data = new String(responseBody);
                    Gson gson = new Gson();
                    DocData docData = gson.fromJson(data, DocData.class);
                    if (docData != null) {
                        onGetDocSuccess(docData);
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                onGetDocFailure();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            }
        });
    }

    private void onGetDocSuccess(DocData docData) {
        this.mDocData = docData;
        mDocAdapter.setDocList(docData.getDocs());
    }

    private void onGetDocFailure() {
        showMsg("获取文档失败!!");
    }

}
